import Vue from 'vue'
import music from '@src/assets/tips.mp3'

export { createNamespace } from '@src/util/create'
export { renderSlots } from '@src/util/render.tsx'
export { addUnit } from '@src/util/format/unit'

export const inBrowser = typeof window !== 'undefined'
export const isServer: boolean = Vue.prototype.$isServer

export function noop () {}

export function isDef (val: unknown): boolean {
  return val !== undefined && val !== null
}

export function isFunction (val: unknown): val is Function {
  return typeof val === 'function'
}

export function isObject (val: unknown): val is Record<any, any> {
  return val !== null && typeof val === 'object'
}

export function isPromise<T = any> (val: unknown): val is Promise<T> {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}

export function get (object: any, path: string): any {
  const keys = path.split('.')
  let result = object
  
  keys.forEach((key) => {
    result = isDef(result[key]) ? result[key] : ''
  })
  
  return result
}

// 播放音乐
export function playMusic(){
  const audio = new Audio(music);
  audio.addEventListener('canplaythrough', () => {
    audio.play();
  });
}

// 直接下载图片 - 避免浏览器直接打开图片
export function downloadImagesDirectly(imageUrl: string, fileName: string) {
  // 创建一个新的 <a> 元素
  const a = document.createElement('a');
  // 设置 <a> 元素的 href 属性为图片的路径
  a.href = imageUrl;
  a.target = '_blank';
  // 设置 download 属性为想要的文件名
  // a.download = fileName;
  // 将 <a> 元素添加到文档中
  document.body.appendChild(a);
  // 触发点击事件
  a.click();
  // 移除 <a> 元素
  document.body.removeChild(a);
}